import React, { useState, useEffect } from 'react';
import { Modal, Table, Tag, message, Button } from 'antd';
import { CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons';
import axios from 'axios';
import moment from 'moment';

const StudentSignInStatus = ({ taskId, visible, onClose }) => {
  const [students, setStudents] = useState([]);
  const [loading, setLoading] = useState(false);
  const [taskInfo, setTaskInfo] = useState(null);

  // 获取签到任务学生列表
  const fetchSignInStudents = async () => {
    if (!taskId) return;
    
    setLoading(true);
    try {
      const response = await axios.get(`/teacher/sign_in/students?task_id=${taskId}`);
      if (response.data && (response.data.code === 2000 || response.data.code === 0)) {
        setStudents(response.data.data?.students || []);
        setTaskInfo(response.data.data?.task || {});
      } else {
        message.error('获取签到学生列表失败');
      }
    } catch (error) {
      console.error('获取签到学生列表出错:', error);
      message.error('获取签到学生列表出错，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 手动帮学生签到
  const manualSignIn = async (studentId) => {
    if (!taskId) return;
    
    try {
      const response = await axios.post('/teacher/sign_in/manual', {
        task_id: taskId,
        student_id: studentId,
        location: "教师手动代签"
      });
      
      if (response.data && (response.data.code === 2000 || response.data.code === 0)) {
        message.success('手动签到成功');
        fetchSignInStudents(); // 刷新列表
      } else {
        message.error(`操作失败: ${response.data?.message || '未知错误'}`);
      }
    } catch (error) {
      console.error('手动签到出错:', error);
      message.error(error.response?.data?.message || '操作失败，请重试');
    }
  };

  // 格式化时间戳为日期时间
  const formatTime = (timestamp) => {
    return timestamp ? moment(timestamp * 1000).format('YYYY-MM-DD HH:mm:ss') : '-';
  };

  // 当模态框可见或任务ID变化时获取数据
  useEffect(() => {
    if (visible && taskId) {
      fetchSignInStudents();
    }
  }, [visible, taskId]);

  // 表格列定义
  const columns = [
    {
      title: '学号',
      dataIndex: 'student_id',
      key: 'student_id',
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '签到状态',
      key: 'signed',
      render: (_, record) => (
        record.signed ? 
          <Tag icon={<CheckCircleOutlined />} color="success">已签到</Tag> : 
          <Tag icon={<CloseCircleOutlined />} color="error">未签到</Tag>
      ),
    },
    {
      title: '签到时间',
      key: 'sign_in_time',
      render: (_, record) => formatTime(record.sign_in_time),
    },
    {
      title: '签到位置',
      dataIndex: 'location',
      key: 'location',
      render: (text) => text || '-',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        !record.signed && (
          <Button 
            type="primary" 
            size="small" 
            onClick={() => manualSignIn(record.student_id)}
          >
            手动签到
          </Button>
        )
      ),
    },
  ];

  return (
    <Modal
      title={`签到任务: ${taskInfo?.description || ''} - 学生签到情况`}
      open={visible}
      onCancel={onClose}
      width={800}
      footer={[
        <Button key="refresh" onClick={fetchSignInStudents}>
          刷新
        </Button>,
        <Button key="close" type="primary" onClick={onClose}>
          关闭
        </Button>,
      ]}
    >
      <Table 
        columns={columns}
        dataSource={students}
        rowKey="student_id"
        loading={loading}
        pagination={{ pageSize: 10 }}
        locale={{ emptyText: '暂无学生数据' }}
      />
    </Modal>
  );
};

export default StudentSignInStatus; 